package com.esunny.online.util;

import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.UUID;

/**
 * @Author: Bcc
 * @Date: 2020/8/8 16:58
 * @Description:
 * @modified By:
 * @version: $
 */
public class CapturePdfUtil {
    /**
     * 生成一本书的缩略图
     * @param inputFile        需要生成缩略图的书籍的完整路径
     * @param outputFile    生成缩略图的放置路径
     */
    public static String generateBookIamge(String inputFile, String outputFile) {
        Document document = null;

        String pngPath = getPngPath();

        outputFile += "pic/" + pngPath;

        try {
            float rotation = 0f;
            //缩略图显示倍数，1表示不缩放，0.5表示缩小到50%
            float zoom = 0.8f;

            document = new Document();
            document.setFile(inputFile);

            BufferedImage p_w_picpath = (BufferedImage)document.getPageImage(0, GraphicsRenderingHints.SCREEN,
                    Page.BOUNDARY_CROPBOX, rotation, zoom);

            Iterator iter = ImageIO.getImageWritersBySuffix("jpg");
            ImageWriter writer = (ImageWriter)iter.next();

            FileOutputStream out = new FileOutputStream(new File(outputFile));
            ImageOutputStream outImage = ImageIO.createImageOutputStream(out);

            writer.setOutput(outImage);
            writer.write(new IIOImage(p_w_picpath, null, null));

        } catch(Exception e) {
            System.out.println( "to generate thumbnail of a book fail : " + inputFile );
            System.out.println( e );
        }

        return pngPath;
    }

    /**
     * 生成图片的相对路径
     * @return 图片的相对路径 例：pic/1.png
     */
    private static String getPngPath(){
        return  getUUID()+".png";
    }


    /**
     * 生成唯一的uuid
     * @return uuid
     */
    private static String getUUID(){
        return UUID.randomUUID().toString().replace("-","");
    }

    public static void main(String[]args){
        String s = CapturePdfUtil.generateBookIamge("E:\\实习\\资料\\市场监察系统前台服务开发公约.pdf", "d:\\online\\upload\\");
        System.out.println(s);
    }
}
